import time
from concurrent.futures import ThreadPoolExecutor, as_completed


# 定义一个简单的任务函数
def square(x):
    print(f"Processing {x} in thread {time.strftime('%H:%M:%S')}")
    time.sleep(1)  # 模拟耗时操作
    if x == 3:
        raise ValueError("x cannot be 3")
    return x * x


# 使用 submit 方法
def use_submit():
    print("Using ThreadPoolExecutor.submit")
    numbers = [1, 2, 3, 4, 5]
    with ThreadPoolExecutor(max_workers=3) as executor:
        # 提交任务
        futures = [executor.submit(square, num) for num in numbers]

        # 等待任务完成并获取结果
        for future in as_completed(futures):
            try:
                result = future.result()
                print(f"Result: {result}")
            except Exception as e:
                print(f"Task failed with exception: {e}")


# 使用 map 方法
def use_map():
    print("Using ThreadPoolExecutor.map")
    numbers = [1, 2, 3, 4, 5]
    with ThreadPoolExecutor(max_workers=3) as executor:
        # 批量提交任务并获取结果
        results = executor.map(square, numbers)

        # 直接迭代结果
        for result in results:
            try:
                print(f"Result: {result}")
            except Exception as e:
                print(f"Task failed with exception: {e}")


# 主函数
if __name__ == "__main__":
    use_submit()
    print("-" * 20)
    use_map()
